package com.example.config;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;

import dev.morphia.Datastore;
import dev.morphia.Morphia;
import dev.morphia.mapping.MapperOptions;

@Configuration
public class MorphiaConfig {
 
    @Bean
    @ConditionalOnMissingBean(Datastore.class)
    public Datastore datastore(MongoProperties mongoProperties) {
 
        MongoClientSettings.Builder settingsBuilder = MongoClientSettings.builder();
 
        //用户凭证
        MongoCredential credential = MongoCredential.createCredential(mongoProperties.getUsername(),
                mongoProperties.getDatabase(), mongoProperties.getPassword());
        settingsBuilder.credential(credential);
 
        //服务器地址
        ServerAddress serverAddress = new ServerAddress(mongoProperties.getHost(), mongoProperties.getPort());
        settingsBuilder.applyToClusterSettings(builder -> builder.hosts(Collections.singletonList(serverAddress)));
 
        //连接接大小
        settingsBuilder.applyToConnectionPoolSettings(builder -> {
            builder.maxSize(5);
            builder.minSize(2);
        });
 
        //超时设置
        settingsBuilder.applyToSocketSettings(builder -> {
            builder.connectTimeout(10, TimeUnit.SECONDS);
            builder.readTimeout(30, TimeUnit.SECONDS);
        });
 
        //读写配置
//        settingsBuilder.readPreference(primaryPreferred());
        settingsBuilder.retryWrites(true);
 
        //创建mongoClient
        MongoClient mongoClient = MongoClients.create(settingsBuilder.build());
 
        //创建Morphia Datastore
        MapperOptions.Builder optionBuilder = MapperOptions.builder();
        optionBuilder.mapSubPackages(true);
        Datastore datastore = Morphia.createDatastore(mongoClient, mongoProperties.getDatabase(),
                optionBuilder.build());
        datastore.getMapper().mapPackage("com.yin.mongotest.model");
        datastore.ensureCaps();
        datastore.ensureIndexes();
        return datastore;
    }
}